package com.meiyu.live.ui.mine;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.android.volley.Response;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.eventbus.RechargeEvent;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.ThirdPayParams;
import com.meiyu.live.net.param.TypeParams;
import com.meiyu.live.net.response.CoinsResponse;
import com.meiyu.live.net.response.OrderResponse;
import com.meiyu.live.net.response.ProductsResponse;
import com.meiyu.live.popj.Product;
import com.meiyu.live.util.RippleUtils;
import com.meiyu.live.util.ToastUtil;
import com.meiyu.live.widget.NetLoadingDailog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 充值
 * Created by zbl on 2016/9/22.
 */
public class RechargeActivity extends BaseActivity implements View.OnClickListener {

    protected NetLoadingDailog dialog_loading;
    private View btn_back, layout_pay_wechat, layout_pay_alipay;
    private TextView tv_mycoins, btn_recharge;
    private ImageView[] rb_pay;
    private List<Product> products;
    private RecyclerView mRecyclerView;

    private int mainColor;

    private int myCoins, canWithdraw;
    private int chargeItemSelectIndex = 0;
    private int payType = 0;
    private LinearLayout selectView;
    GalleryAdapter productsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        init();
        getData();
    }

    private void init() {
        mainColor = getResources().getColor(R.color.main_theme_color);
        dialog_loading = new NetLoadingDailog(this);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        btn_recharge = (TextView) findViewById(R.id.btn_recharge);
        btn_recharge.setOnClickListener(this);
        tv_mycoins = (TextView) findViewById(R.id.tv_mycoins);
        mRecyclerView = (RecyclerView) findViewById(R.id.products);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        products = new ArrayList<Product>();
        productsAdapter = new GalleryAdapter(this);
        mRecyclerView.setAdapter(productsAdapter);

        layout_pay_wechat = findViewById(R.id.layout_pay_wechat);
        layout_pay_alipay = findViewById(R.id.layout_pay_alipay);
        layout_pay_wechat.setOnClickListener(this);
        layout_pay_alipay.setOnClickListener(this);
        RippleUtils.setRippleDrawable(layout_pay_wechat, mainColor);
        RippleUtils.setRippleDrawable(layout_pay_alipay, mainColor);
        rb_pay = new ImageView[]{
                (ImageView) findViewById(R.id.rb_pay_wechat),
                (ImageView) findViewById(R.id.rb_pay_alipay)
        };
        setPayType(1);
    }

    @Override
    public void onClick(View view) {
        if (view == btn_back) {
            finish();
        } else if (view == btn_recharge) {
            postData();
        } else if (view == layout_pay_wechat) {
            setPayType(0);
        } else if (view == layout_pay_alipay) {
            setPayType(1);
        }
    }

    private View.OnClickListener onRechargeItemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            chargeItemSelectIndex = (int) view.getTag();
            LinearLayout ll_cur = (LinearLayout) view;
            selectView.setBackgroundResource(R.drawable.background_recharge_item_n);
            ((TextView) selectView.getChildAt(0)).setTextColor(0x50000000);
            ((TextView) selectView.getChildAt(1)).setTextColor(0x50000000);
            ll_cur.setBackgroundResource(R.drawable.background_recharge_item);
            ((TextView) ll_cur.getChildAt(0)).setTextColor(mainColor);
            ((TextView) ll_cur.getChildAt(1)).setTextColor(mainColor);
            selectView = ll_cur;
        }
    };

    private void setPayType(int payType) {
        this.payType = payType;
        if (payType == 0) {
            rb_pay[0].setImageResource(R.drawable.ic_radio_s);
            rb_pay[1].setImageResource(R.drawable.ic_radio_n);
        } else if (payType == 1) {
            rb_pay[0].setImageResource(R.drawable.ic_radio_n);
            rb_pay[1].setImageResource(R.drawable.ic_radio_s);
        }
    }

    private void getData() {
        dialog_loading.loading();
        BaseBodyParams b = new BaseBodyParams();
        b.setUrl(Constant.UrlParams.MY_COINS);
        request(b, CoinsResponse.class, new Response.Listener<CoinsResponse>() {
            @Override
            public void onResponse(CoinsResponse coinsResponse) {
                if (coinsResponse != null) {
                    myCoins = coinsResponse.getCarrots();
                    canWithdraw = coinsResponse.getCan_withdraw();
                    tv_mycoins.setText(myCoins + "");
                }
            }
        });
        TypeParams typeParams = new TypeParams(2);
        typeParams.setUrl(Constant.UrlParams.AS_PRODUCTS);
        request(typeParams, ProductsResponse.class, new Response.Listener<ProductsResponse>() {
            @Override
            public void onResponse(ProductsResponse productsResponse) {
                dialog_loading.dismissDialog();
                if (productsResponse.getHash() != null && productsResponse.getHash().size() > 0) {
                    products = productsResponse.getHash();
                    productsAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void postData() {
//        if (TextUtils.isEmpty(content)) {
//            ToastUtil.show("请输入建议内容");
//            return;
//        }
        dialog_loading.loading();
        request(new ThirdPayParams(products.get(chargeItemSelectIndex).getId() + "", "0", 1, 3), OrderResponse.class, new Response.Listener<OrderResponse>() {
            @Override
            public void onResponse(OrderResponse orderResponse) {
                dialog_loading.dismissDialog();
                if (orderResponse.getStatusCode() == Constant.StatusCode_Success) {
                    payV2(orderResponse.getOrderInfo());
                } else {
                    ToastUtil.show("支付失败");
                }
            }
        });
    }

    /**
     * 支付宝支付业务
     *
     * @param orderInfo
     */
    public void payV2(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                final Map<String, String> result = alipay.payV2(orderInfo, true);


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String memo = "";
                        if (!"9000".equals(result.get("resultStatus"))) {
                            memo = result.get("memo");
                        } else {
                            BaseBodyParams b = new BaseBodyParams();
                            b.setUrl(Constant.UrlParams.MY_COINS);
                            request(b, CoinsResponse.class, new Response.Listener<CoinsResponse>() {
                                @Override
                                public void onResponse(CoinsResponse coinsResponse) {
                                    if (coinsResponse != null) {
                                        myCoins = coinsResponse.getCarrots();
                                        canWithdraw = coinsResponse.getCan_withdraw();
                                        tv_mycoins.setText(myCoins + "");
                                        EventBus.getDefault().post(new RechargeEvent());
                                    }
                                }
                            });
                            memo = "充值成功";
                        }
                        ToastUtil.show(memo);


                    }
                });

//                Message msg = new Message();
//                msg.what = SDK_PAY_FLAG;
//                msg.obj = result;
//                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public class GalleryAdapter extends
            RecyclerView.Adapter<GalleryAdapter.ViewHolder> {

        /**
         * ItemClick的回调接口
         *
         * @author zhy
         */

        private LayoutInflater mInflater;

        public GalleryAdapter(Context context) {
            super();
            mInflater = LayoutInflater.from(context);
        }


        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View arg0) {
                super(arg0);
            }

            TextView tv_lb;
            TextView tv_coins;
            LinearLayout ll_products;
        }

        @Override
        public int getItemCount() {
            return products.size();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

            LinearLayout view = (LinearLayout) mInflater.inflate(R.layout.item_products,
                    viewGroup, false);
            ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.ll_products = view;
            viewHolder.ll_products.setOnClickListener(onRechargeItemClickListener);
            viewHolder.tv_lb = (TextView) view.findViewById(R.id.tv_lb);
            viewHolder.tv_coins = (TextView) view.findViewById(R.id.tv_coins);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            if (position == 0 && selectView == null) {
                selectView = holder.ll_products;
                selectView.setBackgroundResource(R.drawable.background_recharge_item);
                ((TextView) selectView.getChildAt(0)).setTextColor(mainColor);
                ((TextView) selectView.getChildAt(1)).setTextColor(mainColor);
            }
            holder.tv_lb.setText(products.get(position).getCarrots() + " 钻石");
            holder.tv_coins.setText(products.get(position).getPrice() / 100 + " 元");
            holder.ll_products.setTag(position);
        }


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onError() {
        super.onError();
        dialog_loading.dismissDialog();
    }
}
